<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团队名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入团队名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队编码" prop="teamCode">
        <el-input
          v-model="queryParams.teamCode"
          placeholder="请输入团队编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队类型" prop="teamType">
        <el-select v-model="queryParams.teamType" placeholder="请选择团队类型" clearable>
          <el-option
            v-for="dict in pm_team_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="团队状态" prop="teamStatus">
        <el-select v-model="queryParams.teamStatus" placeholder="请选择团队状态" clearable>
          <el-option
            v-for="dict in pm_team_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:team:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate()"
          v-hasPermi="['pm:team:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['pm:team:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['pm:team:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队ID" align="center" prop="teamId" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="团队编码" align="center" prop="teamCode" />
      <el-table-column label="团队描述" align="center" prop="teamDescription" show-overflow-tooltip />
      <el-table-column label="团队负责人" align="center" prop="teamLeaderName" />
      <el-table-column label="团队类型" align="center" prop="teamType">
        <template #default="scope">
          <dict-tag 
            :options="pm_team_type || []" 
            :value="scope.row.teamType"
            v-if="pm_team_type && pm_team_type.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.teamType || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="团队状态" align="center" prop="teamStatus">
        <template #default="scope">
          <dict-tag 
            :options="pm_team_status || []" 
            :value="scope.row.teamStatus"
            v-if="pm_team_status && pm_team_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.teamStatus || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上级团队" align="center" prop="parentTeamName" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:team:query']"
          >查看</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="isView ? {} : rules" label-width="80px">
        <el-form-item label="团队名称" prop="teamName">
          <el-input v-model="form.teamName" placeholder="请输入团队名称" :disabled="isView" />
        </el-form-item>
        <el-form-item label="团队编码" prop="teamCode">
          <el-input v-model="form.teamCode" placeholder="请输入团队编码" :disabled="isView" />
        </el-form-item>
        <el-form-item label="团队描述" prop="teamDescription">
          <el-input v-model="form.teamDescription" type="textarea" placeholder="请输入团队描述" :disabled="isView" />
        </el-form-item>
        <el-form-item label="团队负责人" prop="teamLeaderId">
          <el-select v-model="form.teamLeaderId" placeholder="请选择团队负责人" clearable :disabled="isView">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="团队类型" prop="teamType">
          <el-select v-model="form.teamType" placeholder="请选择团队类型" :disabled="isView">
            <el-option
              v-for="dict in pm_team_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="团队状态" prop="teamStatus">
          <el-radio-group v-model="form.teamStatus" :disabled="isView">
            <el-radio
              v-for="dict in pm_team_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级团队" prop="parentTeamId">
          <el-tree-select
            v-model="form.parentTeamId"
            :disabled="isView"
            :data="teamTreeData"
            :props="{ value: 'teamId', label: 'teamName', children: 'children' }"
            placeholder="请选择上级团队"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" :disabled="isView" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import { getTeamList, getTeam, delTeam, addTeam, updateTeam, checkTeamCodeUnique, checkTeamNameUnique } from '@/api/pm/team'
import { listUser } from '@/api/system/user'
import { toRefs } from 'vue'

const { proxy } = getCurrentInstance() as any
const { pm_team_type, pm_team_status } = toRefs<any>(proxy?.useDict('pm_team_type', 'pm_team_status'))

const teamList = ref([])
const open = ref(false)
const loading = ref(true)
const isView = ref(false) // 是否为查看模式
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const userList = ref([])
const teamTreeData = ref([])

const queryFormRef = ref<ElForm>()
const formRef = ref<ElForm>()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  teamName: null,
  teamCode: null,
  teamType: null,
  teamStatus: null,
  teamLeaderId: null,
  parentTeamId: null
})

// 表单参数
const form = ref({
  teamId: null,
  teamName: null,
  teamCode: null,
  teamDescription: null,
  teamLeaderId: null,
  teamType: "project",
  teamStatus: "0",
  parentTeamId: null,
  sortOrder: 0,
  remark: null
})

// 表单校验
const rules = reactive({
  teamName: [
    { required: true, message: '团队名称不能为空', trigger: 'blur' }
  ],
  teamCode: [
    { required: true, message: '团队编码不能为空', trigger: 'blur' }
  ],
  teamType: [
    { required: true, message: '团队类型不能为空', trigger: 'change' }
  ],
  teamStatus: [
    { required: true, message: '团队状态不能为空', trigger: 'change' }
  ]
})

/** 查询团队管理列表 */
function getList() {
  loading.value = true
  getTeamList(queryParams).then(response => {
    teamList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    teamId: null,
    teamName: null,
    teamCode: null,
    teamDescription: null,
    teamLeaderId: null,
    teamStatus: '0',
    teamType: 'project',
    parentTeamId: null,
    sortOrder: 0,
    remark: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection: any[]) {
  ids.value = selection.map(item => item.teamId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  isView.value = false
  open.value = true
  title.value = '添加团队管理'
}

/** 查看按钮操作 */
function handleView(row: any) {
  reset()
  const teamId = row.teamId
  getTeam(teamId).then(response => {
    form.value = response.data
    isView.value = true
    open.value = true
    title.value = '查看团队管理'
  })
}

/** 修改按钮操作 */
function handleUpdate(row?: any) {
  reset()
  const teamId = row?.teamId || ids.value[0]
  getTeam(teamId).then(response => {
    form.value = response.data
    isView.value = false
    open.value = true
    title.value = '修改团队管理'
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      if (form.value.teamId != null) {
        updateTeam(form.value).then(response => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addTeam(form.value).then(response => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row?: any) {
  const teamIds = row?.teamId || ids.value
  ElMessageBox.confirm('是否确认删除团队管理编号为"' + teamIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(function() {
    return delTeam(teamIds)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

/** 导出按钮操作 */
function handleExport() {
  // TODO: 实现导出功能
  ElMessage.info('导出功能开发中...')
}

/** 获取用户列表 */
function getUserList() {
  listUser({ pageNum: 1, pageSize: 1000 }).then(response => {
    userList.value = response.rows
  })
}

/** 获取团队树数据 */
function getTeamTreeData() {
  getTeamList({}).then(response => {
    teamTreeData.value = response.rows
  })
}

onMounted(() => {
  getList()
  getUserList()
  getTeamTreeData()
})
</script>